<template>
  <template v-if="icon">
    <!-- html字符串 -->
    <rich-text v-if="icon.htmlStr" :nodes="icon.htmlStr"></rich-text>
    <!-- font字体图标 -->
    <text v-else-if="icon.cssClass" :class="[icon.cssClass, className]"></text>
    <template v-else-if="icon.imagePath">
      <!-- base64格式内容 -->
      <image
        v-if="isBase64Image(icon.imagePath)"
        :class="[className]"
        :src="icon.imagePath"
        alt=""
      />
      <!-- UTF-8 表情字符 -->
      <view v-else-if="isBase64(icon.imagePath)" :class="[className, ns.e('emoji')]">
        {{ base64ToStr(icon.imagePath) }}
      </view>
      <!-- SVG 内容 -->
      <image
        v-else-if="isSvg(icon.imagePath)"
        :class="className"
        :src="handleSvg(icon.imagePath)"
      />
      <!-- 以svg结尾 -->
      <template v-else-if="icon.imagePath.endsWidth('svg')">
        <!-- 远程svg -->
        <image
          v-if="icon.imagePath.startsWith('http')"
          :class="className"
          :src="icon.imagePath"
          alt=""
        />
        <!-- 本地svg -->
        <image v-else :class="className" :src="BaseUrl + icon.imagePath" alt="" />
      </template>
      <!-- 远程图片 -->
      <image
        v-else-if="icon.imagePath.startsWith('http')"
        :class="className"
        :src="icon.imagePath"
        alt=""
      />
      <!-- 本地图片 -->
      <image v-else :class="className" :src="BaseUrl + icon.imagePath" alt="" />
    </template>
    <template v-else-if="icon.rawContent">
      <image
        v-if="isSvg(icon.rawContent)"
        :class="className"
        :src="handleSvg(icon.rawContent)"
      ></image>
      <image v-else :class="className" :src="icon.rawContent" alt="" />
    </template>
  </template>
</template>
<script lang="ts" setup>
import { useNamespace } from '@/use'
import { PropType } from 'vue'
import { isBase64Image, isBase64, base64ToStr, isSvg } from '@ibiz-template/core'
import { base64Encode } from '@/utils'

const props = defineProps({
  icon: {
    type: Object as PropType<IData>,
  },
  baseDir: {
    type: String,
    default: 'images',
  },
  size: {
    type: String as PropType<'small' | 'medium' | 'large'>,
  },
})

const BaseUrl = `${ibiz.env.assetsUrl}/${props.baseDir}/`

const handleSvg = (str: string) => {
  const base64Svg = base64Encode(unescape(encodeURIComponent(str)))
  const imgUrl = `data:image/svg+xml;base64,${base64Svg}`
  return imgUrl
}

const ns = useNamespace('icon')
const className = computed(() => [ns.b()])
</script>
<style lang="scss">
@include b(icon) {
  display: inline-block;
  width: 100%;
  height: 100%;
}
</style>
